package com.wmh.baseservice.operationaid.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.operationaid.entity.FilterTemplate;
import com.wmh.baseservice.operationaid.enums.FilterTemplateType;
import com.wmh.baseservice.operationaid.mapper.FilterTemplateMapper;
import com.wmh.baseservice.operationaid.pojo.vo.filterTemplate.FilterTemplateCommitReqVO;
import com.wmh.baseservice.operationaid.service.FilterTemplateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @author dongaolong
 * @description 针对表【operation_aid_filter_template】的数据库操作Service实现
 * @createDate 2023-06-13 09:54:35
 */
@Slf4j
@Service
public class FilterTemplateServiceImpl extends ServiceImpl<FilterTemplateMapper, FilterTemplate>
        implements FilterTemplateService {

    /**
     * 校验任务模板唯一名称
     *
     * @param adId         管理员id
     * @param templateId   模板id
     * @param templateName 模板名称
     */
    private void checkTaskTemplateUniqueName(Long adId, Long templateId, String templateName, FilterTemplateType type) {
        if (getOne(new LambdaQueryWrapperX<FilterTemplate>()
                .eq(FilterTemplate::getName, templateName)
                .eq(FilterTemplate::getAdId, adId)
                .eq(FilterTemplate::getType,type.getValue())
                .ne(templateId != null, FilterTemplate::getId, templateId)) != null) {
            throw new ServiceException("该模板名称已经存在 ");
        }
    }

    @Override
    public Long commitFilterTemplate(Long adId, FilterTemplateCommitReqVO reqVO) {
        checkTaskTemplateUniqueName(adId, reqVO.getTemplateId(), reqVO.getTemplateName(), reqVO.getType());
        FilterTemplate filterTemplate = new FilterTemplate().setId(reqVO.getTemplateId()).setParams(reqVO.getParamList())
                .setAdId(adId).setName(reqVO.getTemplateName()).setType(reqVO.getType().getValue());
        saveOrUpdate(filterTemplate);
        return filterTemplate.getId();
    }
}
